from paho.mqtt import client as mqtt
import uuid
import queue
import json

from mqtt.data_parse import DataParse

message_queue = queue.Queue()


class MqttManager:

    def __init__(self, mt_ip, mt_user, mt_pwd, mqttClient=mqtt.Client(str(uuid.uuid4()))):
        self.mt_ip = mt_ip
        self.mt_user = mt_user
        self.mt_pwd = mt_pwd
        self.mqttClient = mqttClient

    def on_connect(self, client, userdata, flags, rc):
        rc_status = ["连接成功", "协议版本不正确", "客户端标识符无效", "服务器不可用", "用户名或密码不正确", "未经授权"]
        print("connect：", rc_status[rc])
        # self.on_subscribe("device01/#")

    def on_message(self, client, userdata, msg):
        """一旦订阅到消息, 回调此方法"""
        # print("主题:" + msg.topic + " 消息:" + str(msg.payload.decode('gb2312')))
        try:
            result = msg.payload.decode('gb18030', 'ignore')
            # print("主题:" + msg.topic + " 消息:" + str(result))
            # 将JSON字符串解析成字典
            data = json.loads(str(result))

            snText = DataParse().extractSN(msg.topic)
            # print(snText)
            # 插入新的键值对
            data["sn_id"] = snText

            # print(data)
            # 将更新后的字典转换回JSON字符串
            new_json = json.dumps(data)
            # print(f"on_message:{new_json}")
            # 将收到的消息放入到消息队列中
            message_queue.put(data)
        except UnicodeEncodeError:
            print("字符包含了无法解析的编码")
        except:
            print("未知异常")

    def mqtt_connect(self):
        """连接MQTT服务器"""
        # mqttClient = mqtt.Client(str(uuid.uuid4()))
        self.mqttClient.on_connect = self.on_connect  # 返回连接状态的回调函数
        self.mqttClient.on_message = self.on_message
        MQTTHOST = self.mt_ip  # MQTT服务器地址
        MQTTPORT = 1883  # MQTT端口
        self.mqttClient.username_pw_set(self.mt_user, self.mt_pwd)  # MQTT服务器账号密码, 无密码时注释即可
        self.mqttClient.connect(MQTTHOST, MQTTPORT, 60)
        self.mqttClient.loop_start()  # 启用线程连接
        return self.mqttClient

    def mqtt_publish(self, topicName, text):
        """发布主题为'mqtt/app',内容为'Demo text',服务质量为2"""
        if not self.mqttClient.is_connected():
            self.mqttClient = self.mqtt_connect()
        self.mqttClient.publish(topicName, text, 0)
        # self.mqttClient.loop_stop()

    def on_subscribe(self, topicName):
        """订阅主题：mqtt/app"""
        if not self.mqttClient.is_connected():
            self.mqttClient = self.mqtt_connect()
        self.mqttClient.subscribe(topicName, 0)
